package com.objectdraw.client.objectdraw;
import java.awt.*;
import java.awt.event.*;

/**
 * controls mouse events for drawing ovals
 * @author jgulik, cfruehan
 *
 */
public class OvalTool implements Tool {

	protected DrawingCanvas canvas;
	protected Point startingMousePosition;
	protected Color saveColor;

	/**
	 * instantiates the tool
	 * @param canvas the canvas upon which the tool acts
	 */
	public OvalTool(DrawingCanvas canvas) {
		this.canvas = canvas;
	}

	/**
	 * draw an oval at position (x,y) with supplied height and width
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 */
	protected void drawOval(int x, int y, int width, int height) {
		int ovalX = x;
		int ovalY = y;
		int ovalWidth = width;
		int ovalHeight = height;
		if (width < 0) {
			ovalX = x + width;
			ovalWidth = -width;
		} 
		if (height < 0) {
			ovalY = y + height;
			ovalHeight = -height;
		}
		Graphics iBGraphics = canvas.getImageBufferGraphics();
		iBGraphics.drawOval(ovalX, ovalY, ovalWidth, ovalHeight);

		canvas.repaint();
	}

	/**
	 * start a new oval object at point supplied in event e
	 */
	public void mousePressed(MouseEvent e)  {
		/* Establish starting point for next drawing */
		Graphics iBGraphics = canvas.getImageBufferGraphics();
		startingMousePosition = e.getPoint();
		saveColor = canvas.penColor;
		
		iBGraphics.setColor(Color.lightGray);
		drawOval(startingMousePosition.x,
				startingMousePosition.y, 0,0);

	}
	/**
	 * draw a temporary oval using the initial point and the current mouse location
	 */
	public void mouseDragged(MouseEvent e)  {
		Graphics iBGraphics = canvas.getImageBufferGraphics();

		iBGraphics.setColor(Color.lightGray);

		/* draw updated temporary line */
		Point newMousePosition = e.getPoint();
		drawOval(startingMousePosition.x,startingMousePosition.y,
				newMousePosition.x -startingMousePosition.x,
				newMousePosition.y- startingMousePosition.y);

	}

	/**
	 * draw an oval using the initial point and the release point.  push the oval object 
	 * onto the object list
	 */
	public void mouseReleased(MouseEvent e) { 
		Graphics iBGraphics = canvas.getImageBufferGraphics();
		iBGraphics.setColor(saveColor);
		drawOval(startingMousePosition.x, startingMousePosition.y,
				e.getPoint().x -startingMousePosition.x,
				e.getPoint().y - startingMousePosition.y);

		OvalObject myoval=new OvalObject(startingMousePosition,e.getPoint(),canvas.getImageBufferGraphics().getColor());
		IDrawingObjectLink myovalLink=new IDrawingObjectLink(myoval);
		myovalLink.next=canvas.firstObject;
		canvas.push(myovalLink);
	}
}
